//
//  touchView.m
//  自定义可动图表
//
//  Created by yuklng on 16/2/17.
//  Copyright © 2016年 yuklng. All rights reserved.
//

#import "touchView.h"
#import "pointObject.h"

@implementation touchView{
//  点坐标数组
//    NSMutableArray* _cloudArray;
    
//  背景线端
    CAShapeLayer *layer;
    
//  最高行/最低行
    int topLine;
    int lowestLine;
    
//  用户进行操作的对象
    pointObject* nowPoint;
}

-(id)initWithFrame:(CGRect)frame{
    self =[self initWithFrame:frame topLine:30 lowestLine:17 autoLayout:YES];
    if(self){
//        [self setBackgroundColor:[UIColor orangeColor]];
//        
////      初始化视图默认x间距与y间距
//        _xSpacing =_width/8;
//        _ySpacing =35;
//        
////      描绘视图背景
//        [self drawBack];
    }
    return self;

}

//参数-1.frame(坐标、大小) 2.最高值 3.最低值 4.是否自适应?是则依照 用户所给的大小/(最高值-最低值)布局，否则根据(最高值-最低值)*y间距进行布局(待扩展，现默认自适应)
-(id)initWithFrame:(CGRect)frame topLine:(int)maxNumber lowestLine:(int)minNumber autoLayout:(BOOL)autoLayout{
    self = [super initWithFrame:frame];
    if(self){
        [self setBackgroundColor:[UIColor clearColor]];
        
        //      初始化视图默认x间距与y间距
        _xSpacing =_width/8;
        _ySpacing =40;
        
        //      初始化行数
        topLine =maxNumber;
        lowestLine =minNumber;
        
        double viewHeight = (topLine-lowestLine)*_ySpacing;
        //      描绘视图背景
        if (autoLayout) {
            [self initFormView:frame row:(topLine-lowestLine)];
            viewHeight = (topLine-lowestLine)*_ySpacing;
        }else{
            [self drawBack];
            viewHeight = frame.size.height;
        }
        
        _cloudArray =[[NSMutableArray alloc] init];
        for (int i =0; i <8; i++) {
            pointObject* point =[[pointObject alloc] init];
            
            point.row =2+arc4random()%5;
            
            CGFloat xPoint = _xSpacing/2 +(i*_xSpacing);
            //  选择自动模式时不引用frame

            CGFloat yPoint = self.frame.size.height-(point.row -lowestLine)*_ySpacing;
            CGPoint nPoint ={xPoint,yPoint};
            point.origin =nPoint;
            
            CGSize size ={_xSpacing,_ySpacing};
            point.sideLength =size;
            [_cloudArray addObject:point];
            
        };
    }
    
    return self;
}

#pragma mark - 设置图表数据
-(void)setDataArray:(NSArray*)array{
    _cloudArray =[NSMutableArray new];
    _xSpacing =_width/[array count];
    for (int i =0; i <[array count]; i++) {
        pointObject* point =[[pointObject alloc] init];
        
        point.row =[array[i] intValue];
        
        CGFloat xPoint = _xSpacing/2 +(i*_xSpacing);
        //  选择自动模式时不引用frame
        
        CGFloat yPoint = self.frame.size.height-(point.row -lowestLine)*_ySpacing;
        CGPoint nPoint ={xPoint,yPoint};
        point.origin =nPoint;
        
        CGSize size ={_xSpacing,_ySpacing};
        point.sideLength =size;
        [_cloudArray addObject:point];
    };
    [self setNeedsDisplay];
}



//根据行间距设置视图长度
-(void)initFormView:(CGRect)frame row:(int)row{
    self.frame =CGRectMake(frame.origin.x, frame.origin.y, frame.size.width-1, (row*_ySpacing)+25);
    [self.layer removeFromSuperlayer];
    
    for (int i =0; i<=row; i++) {
        UIBezierPath* path = [UIBezierPath bezierPath];
        // 添加路径[1条点(100,100)到点(200,100)的线段]到path
        [path moveToPoint:CGPointMake(0, self.frame.size.height-3-(_ySpacing*i))];
        [path addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height-3-(_ySpacing*i))];
        // 将path绘制出来
        layer = [CAShapeLayer layer];
        layer.frame         = self.bounds;                // 与showView的frame一致
        layer.lineWidth     = 0.3f;                           // 线条宽度
        layer.path          = path.CGPath;                    // 从贝塞尔曲线获取到形状
        layer.strokeColor   = [UIColor whiteColor].CGColor;   // 边缘线的颜色
        layer.fillColor     = [UIColor clearColor].CGColor;   // 闭环填充的颜色
        
        [self.layer addSublayer:layer];
    }
    
}


//正常的描绘背景方法
-(void)drawBack{
    int viewHeight =(int)self.frame.size.height;
    double remainder =viewHeight%(int)_ySpacing;
    double row =(viewHeight-remainder)/_ySpacing;
    for (int i =0; i<=row; i++) {
        UIBezierPath* path = [UIBezierPath bezierPath];
        // 添加路径[1条点(100,100)到点(200,100)的线段]到path
        [path moveToPoint:CGPointMake(0, self.frame.size.height-3-(_ySpacing*i))];
        [path addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height-3-(_ySpacing*i))];
        // 将path绘制出来
        layer = [CAShapeLayer layer];
        layer.frame         = self.bounds;                // 与showView的frame一致
        layer.lineWidth     = 0.6f;                           // 线条宽度
        layer.path          = path.CGPath;                    // 从贝塞尔曲线获取到形状
        layer.strokeColor   = [UIColor whiteColor].CGColor;   // 边缘线的颜色
        layer.fillColor     = [UIColor clearColor].CGColor;   // 闭环填充的颜色
        
        [self.layer addSublayer:layer];
    }
    
}


-(void)drawRect:(CGRect)rect{
    [super drawRect:rect];
    
    for (int i =0; i<=topLine-lowestLine; i++) {
//        path = [UIBezierPath bezierPath];
//        // 添加路径[1条点(100,100)到点(200,100)的线段]到path
//        [path moveToPoint:CGPointMake(0, self.frame.size.height-3-(_ySpacing*i))];
//        [path addLineToPoint:CGPointMake(self.frame.size.width, self.frame.size.height-3-(_ySpacing*i))];
    NSString *string = [NSString stringWithFormat:@"%d°",lowestLine+i];
    [string drawInRect:CGRectMake(self.frame.size.width-15, self.frame.size.height-3-(_ySpacing*i)-15, 15, 20) withAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:8],NSForegroundColorAttributeName:[UIColor whiteColor]}];
    }
    
    if ([_cloudArray count]>0) {
        for (int i =0; i <[_cloudArray count]-1; i++) {
            //绘线
            CGContextRef ctx = UIGraphicsGetCurrentContext();
            
            pointObject* indexPoint =_cloudArray[i];
            
            pointObject* endPoint =_cloudArray[i+1];
            
            CGPoint aPoints[2];//坐标点
            aPoints[0] =CGPointMake(indexPoint.origin.x, indexPoint.origin.y-3);//坐标1
            aPoints[1] =CGPointMake(endPoint.origin.x, endPoint.origin.y-3);//坐标2
            
            CGContextSetRGBStrokeColor(ctx, 1, 1, 1, 1);//设置颜色
            
            //  上下文、坐标点数组、粗度
            CGContextAddLines(ctx, aPoints, 2);//添加线
            
            CGContextSetLineWidth(ctx, 1.2);//设置线段粗值
            
            CGContextDrawPath(ctx, kCGPathStroke); //根据坐标绘制路径
            
            //圆点直径数值
            int diameter =6;
            UIBezierPath* path1=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(aPoints[0].x-3, aPoints[0].y-3, diameter, diameter)];
            //实心颜色
            [[UIColor whiteColor] setFill];
            //实心
            [path1 fill];
            
            //y绘线
            CGContextRef ctx2 = UIGraphicsGetCurrentContext();
            
            CGPoint bPoints[2];//坐标点
            bPoints[0] =CGPointMake(aPoints[0].x, self.frame.size.height-3);//坐标1
            bPoints[1] =CGPointMake(aPoints[0].x, aPoints[0].y-3);//坐标2
            
            CGContextSetRGBStrokeColor(ctx2, 1, 1, 1, 0.6);//设置颜色
            //  上下文、坐标点数组、粗度
            CGContextAddLines(ctx2, bPoints, 2);//添加线
            CGContextSetLineWidth(ctx2, 0.3);//设置线段粗值
            CGContextDrawPath(ctx2, kCGPathStroke); //根据坐标绘制路径
            
            if (i ==[_cloudArray count]-2) {
                int diameter =6;
                UIBezierPath* path1=[UIBezierPath bezierPathWithOvalInRect:CGRectMake(aPoints[1].x-3, aPoints[1].y-3, diameter, diameter)];
                //实心颜色
                [[UIColor whiteColor] setFill];
                //实心
                [path1 fill];
                
                //y绘线
                CGContextRef ctx2 = UIGraphicsGetCurrentContext();

                CGPoint bPoints[2];//坐标点
                bPoints[0] =CGPointMake(aPoints[1].x, self.frame.size.height-3);//坐标1
                bPoints[1] =CGPointMake(aPoints[1].x, aPoints[1].y-3-3);//坐标2
                
                CGContextSetRGBStrokeColor(ctx2, 1, 1, 1, 0.6);//设置颜色
                //  上下文、坐标点数组、粗度
                CGContextAddLines(ctx2, bPoints, 2);//添加线
                CGContextSetLineWidth(ctx2, 0.3);//设置线段粗值
                CGContextDrawPath(ctx2, kCGPathStroke); //根据坐标绘制路径
            }
            
        }

    }
    
}

#pragma mark - UIControl Override -

/** Tracking is started **/
-(BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super beginTrackingWithTouch:touch withEvent:event];
    //We need to track continuously
    NSLog(@"启动触摸跟踪方法");
    CGPoint lastPoint = [touch locationInView:self];
    
    for (int i =0; i <[_cloudArray count]; i++) {
        pointObject* point =_cloudArray[i];
        NSLog(@"%d:%@",i,point);
        
        LLScope LLScope =[point getScope];
        if (lastPoint.x>LLScope.xMin&&lastPoint.x<LLScope.xMax&&lastPoint.y>LLScope.yMin&&lastPoint.y<LLScope.yMax*2)
            
        {
            nowPoint =point;
            
            return YES;
        }
    }
    return NO;
}

/** Track continuos touch event (like drag) **/
-(BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super continueTrackingWithTouch:touch withEvent:event];
    
    //Get touch location
    CGPoint lastPoint = [touch locationInView:self];
    
    //Use the location to design the Handle
//    [self movehandle:lastPoint];
    

    pointObject* point =nowPoint;
    LLScope LLScope =[point getScope];
    if (lastPoint.x>LLScope.xMin||lastPoint.x<LLScope.xMax) {
        CGPoint size ={point.origin.x,lastPoint.y};
        point.origin = size;
        [self setNeedsDisplay];
    }

    
    NSLog(@"当前点击的是:x-%f y-%f",lastPoint.x,lastPoint.y);
    
    //Control value has changed, let's notify that
    [self sendActionsForControlEvents:UIControlEventValueChanged];
    
    return YES;
}

/** Track is finished **/
-(void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    [super endTrackingWithTouch:touch withEvent:event];
    NSLog(@"物体从屏幕上抬起了");
    
    CGPoint lastPoint = [touch locationInView:self];
    for (int i =0; i<=topLine-lowestLine; i++) {
        CGFloat max =self.frame.size.height-(_ySpacing*i);
        CGFloat min =self.frame.size.height-(_ySpacing*i)-_ySpacing/2;
        CGFloat max2 =self.frame.size.height-(_ySpacing*(i+1));
        if (i!=topLine-lowestLine) {
            if (lastPoint.y>min&&lastPoint.y<max) {
                pointObject* point =nowPoint;
                NSLog(@"处于第%d行,值为:%d",i,point.row);
                
                NSLog(@"比较小，放下小于线 %d",i+lowestLine);
                point.row =i+lowestLine;
                
                //因为是倒序比较，所以比较大的反而是比较小的
                CGPoint size ={point.origin.x,max};
                point.origin = size;
                [self setNeedsDisplay];
                
                [self delegateControl];
                
            }else if (lastPoint.y>max2&&lastPoint.y<min) {
                pointObject* point =nowPoint;
                NSLog(@"处于第%d行,值为:%d",i,point.row);
                
                NSLog(@"比较大，放入大于线 %d",i+1+lowestLine);
                point.row =i+1+lowestLine;
                
                CGPoint size ={point.origin.x,max2};
                point.origin = size;
                [self setNeedsDisplay];
                
                [self delegateControl];
            }

        }else{
            if (lastPoint.y<max) {
                pointObject* point =nowPoint;
                NSLog(@"处于第%d行,值为:%d",i,point.row);
                
                NSLog(@"比较小，放下小于线 %d",i+lowestLine);
                point.row =i+lowestLine;
                
                //因为是倒序比较，所以比较大的反而是比较小的
                CGPoint size ={point.origin.x,max};
                point.origin = size;
                [self setNeedsDisplay];
                
                [self delegateControl];
                
            }
        }
        
    }
    
}

-(void)delegateControl{
    NSArray* passingArray =[[NSArray alloc] initWithArray:_cloudArray];
    NSMutableArray* dataArray =[[NSMutableArray alloc] init];
    for (int i =0; i <[passingArray count]; i++) {
        pointObject* pObject =passingArray[i];
        [dataArray addObject:[NSNumber numberWithInt:pObject.row]];
    }
    [_delegate touchSwitch:YES dataArray:dataArray];
}

@end
